package main

import (
	"fmt"
	"iot-base/common/config"
	"iot-base/common/custom"
	"iot-base/common/dbconn"
	"iot-base/common/dbobj"
	"iot-base/common/logger"
	"iot-base/common/monitor"
	"iot-base/common/token"
	"iot-base/common/webapi"
	"iot-base/tm/common/alarmapi"
	"iot-base/tm/common/dataapi"
	_ "iot-base/tm/common/dbinit"
	"iot-base/tm/common/fileapi"
	"iot-base/tm/common/maintain"
	"iot-base/tm/common/picapi"
	"iot-base/tm/common/serviceapi"
	"iot-base/tm/common/stateapi"
	"iot-base/tm/common/superadmin"
	"iot-base/tm/common/systemapi"
	"iot-base/tm/common/templateapi"
	"iot-base/tm/common/thingapi"

	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	//"iot-base/common/tunnel/csvr"

	"github.com/gin-gonic/gin"
)

type thingLocal struct {
	dbobj.Thing
	SNO int `json:"sno"`
}

func createByEdge(c *gin.Context) {
	edgeID := c.Param("edgeID")
	var things []thingLocal
	if err := c.ShouldBindJSON(&things); err != nil {

		webapi.SendError(err.Error(), webapi.DBError, c)
		return
	}
	createByEdgeImpl(edgeID, &things)
	webapi.SendOK(c)

}
func createByEdgeImpl(edgeID string, pthings *[]thingLocal) {
	edge := dbobj.Thing{
		UID: edgeID,
	}
	dbconn.DBConnection.First(&edge)
	tsEdge := dbobj.ThingStation{
		ThingID: edgeID,
		ModelID: "IOTBASEmEdgeCTL",
		//StationID:
	}
	dbconn.DBConnection.First(&tsEdge)

	if edge.ModelID == "IOTBASEmEdgeCTL" {
		for _, thing := range *pthings {
			//pThing := &things[i]
			//pThing.StationID = pEdge.Thing.StationID
			thing.ProxyThingID = edgeID
			thing.IsProxy = false
			thing.Thing.ProtocolPath = ""
			if thing.UID != edgeID {

				dbconn.DBConnection.Save(&thing.Thing)
				ts := dbobj.ThingStation{
					ThingID:   thing.UID,
					StationID: tsEdge.StationID,
					SNO:       thing.SNO,
					ModelID:   thing.Thing.ModelID,
				}
				dbconn.DBConnection.Save(&ts)
			}

		}
	}
}

func main() {
	logger.Log.Warn("---------TM in Cloud---------running----------")
	//go csvr.BeginSvr(39999)
	author := token.AuthMiddleware()
	r, api, cfg := thingapi.InitThing(author)
	try := r.Group("/others/")
	try.GET("tryHeart", func(c *gin.Context) {
		c.String(http.StatusOK, "iot-base a connection to the endless world")
	})
	systemapi.InitAPI(cfg)
	templateapi.InitPickTemplateAPI(cfg)
	custom.InitAPI(api)
	fileapi.InitAPI(api)
	superadmin.InitUser(api)
	stateapi.InitOnlineAPI(api)
	thingapi.BeginMsgSocketIO(r)
	thingapi.InitConfigAPI(cfg)
	byEdge := cfg.Group("/syncByEdge")
	byEdge.PUT("/:edgeID", createByEdge)

	/*if cfg != nil {
		cfg.Use(token.AuthMiddleware())
		logger.Log.Info("--------------TM create middleware--------------")
	}*/
	if api != nil {
		dataapi.InitDataAPI(api)
		alarmapi.InitAlarmAPI(api)
		serviceapi.InitService(api)
		maintain.InitMaintainAPI(api)
		picapi.InitPicApi(api)
		//api.Use(token.AuthMiddleware())
		file, _ := exec.LookPath(os.Args[0])
		path, err := filepath.Abs(file)
		//dir = "d:/work/node/TS/bin"
		//dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
		dir := filepath.Dir(path)
		if strings.Index(dir, "bin") < 0 {
			dir = dir + "/bin"
		}

		if err != nil {
			log.Fatal(err)
		}
		dir = dir + "/dist"
		fmt.Println("--------------------", dir)
		r.StaticFS("/static", http.Dir(dir))
		r.Static("/js", dir+"/js")
		r.Static("/css", dir+"/css")
		r.Static("/img", dir+"/img")
		r.Static("/assets", dir+"/assets")
		r.Static("/baiduOffLineMap", dir+"/baiduOffLineMap")

		r.LoadHTMLFiles(dir + "/index.html")
		r.GET("/", func(context *gin.Context) {
			context.HTML(http.StatusOK, "index.html", nil)
		})
		r.StaticFS("/ui/", http.Dir(dir))
		monitor.InitSelfPicker()
		lport := fmt.Sprintf(":%v", config.SelfOption.MaintainPort)

		//r.Use(gzip.Gzip(gzip.DefaultCompression))
		r.Run(lport)
	}

}
